import SwiftUI
import Kingfisher

struct FoodTypeView: View {
    
    @Binding var selectedType: FoodTypeItemRespModel?
    @State private var foodTypes: [FoodTypeItemRespModel] = []
    
    @Environment(PopupModel.self) private var popup
    @Environment(NetworkMonitor.self) private var networkMonitor
    
    // 全部餐饮类型
    var isAllFoodType: Bool {
        selectedType == nil
    }
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            // 全部
            HStack(spacing: 7.0) {
                Button {
                    Log.debug("全部食物类型")
                    selectedType = nil
                } label: {
                    Text("全部")
                        .font(.alibabaPuHuiTi(size: 16.0, weight: isAllFoodType ? .semiBold : .regular))
                        .foregroundStyle(.fs020000)
                        .frame(height: 48.0)
                }
                .padding(.horizontal, 20)
                .background {
                    Capsule()
                        .fill(isAllFoodType ? .fsFFC600 : .fsFFFFFF)
                }
                // 分类
                ForEach(foodTypes) { type in
                    HStack(spacing: 6.0) {
                        KFImage(URL(string: type.picFile?.url ?? ""))
                            .placeholder({
                                WebImageLoadingView()
                            })
                            .onFailureImage(.iconPlaceholderFood)
                            .resizable()
                            .frame(width: 40.0, height: 40.0)
                            .clipShape(Circle())
                            .overlay {
                                Circle()
                                    .stroke(.white, lineWidth: 2.0)
                            }
                        Text(type.name)
                            .font(
                                .alibabaPuHuiTi(
                                    size: 16.0,
                                    weight: textWeightForType(type))
                            )
                            .foregroundStyle(textColorForTypeName())
                    }
                    .padding(.vertical, 4.0)
                    .padding(.leading, 4.0)
                    .padding(.trailing, 16.0)
                    .background(content: {
                        Capsule()
                            .fill(bgColorForTypeName(type))
                    })
                    .onTapGesture {
                        Log.debug("点击了\(type.name)")
                        selectedType = type
                    }
                }
            }
            .padding(.horizontal, 12.0)
        }
        .onAppear {
            getCategories()
        }
        .onChange(of: networkMonitor.isConnected) { oldValue, newValue in
            if newValue {
                getCategories()
            }
        }
        
    }
    
    private func textColorForTypeName() -> Color {
        .fs020000
    }
    
    private func textWeightForType(_ model: FoodTypeItemRespModel) -> Font.AlibabaPuHuiTiWeight {
        selectedType == model ? .semiBold : .regular
    }
    
    private func bgColorForTypeName(_ model: FoodTypeItemRespModel) -> Color {
        selectedType == model ? .fsFFC600 : .fsFFFFFF
    }
    
    func getCategories() {
        Task {
            do {
                let target = API.categoryList
                let categories = try await NetworkManager.shared.request(
                    target, responseType: FoodTypeListRespModel.self)
                foodTypes = categories.data.first(where: {
                    $0.name == "餐饮_Restoran"
                })?.children ?? []
            } catch {
                if let error = error as? BaseError {
                    popup.show(content: error.message)
                }
            }
        }
    }
}

#Preview {
    FoodTypeView(selectedType: .constant(nil))
        .environment(PopupModel())
}
